#include <stdio.h>
#include <string.h>
#include <time.h>
typedef unsigned int uint32_t;
typedef unsigned char uint8_t;

int crc32(uint32_t * buffer,uint32_t length) {
        uint32_t xbit;
        uint32_t data;
        uint32_t CRC32 = 0xFFFFFFFF;
        uint32_t bits;
        uint32_t dwPolynomial = 0x04c11db7;

        for (int i = 0; i < length; i++) {
            xbit = 1 << 31;
            data = buffer[i];
            for (bits = 0; bits < 32; bits++) {

                if ((CRC32 & 0x80000000) != 0) {
                    CRC32 <<= 1;
                    CRC32 ^= dwPolynomial;
                } else {
                    CRC32 <<= 1;
                }
                if ((data & xbit) != 0) {
                    CRC32 ^= dwPolynomial;
                }
                xbit = xbit >>  1;
            }
        }
        return CRC32;
    }


int main(int argc,char **argv)
{
	//char argv[2][100]={"123","work.bin"};
	if(argv[2][0] == '1')
	printf("打开文件:%s 成功!\n",argv[1]);
	//FILE *fp=fopen(argv[1],"rb+");
	char ASD[128]={0};

	uint8_t cInput=0;
	uint8_t Buffer[1024*50];
	uint32_t BUF[1024*50] ;
	
	FILE *fp2=fopen(argv[1],"ab+");
	
    fseek(fp2,0,SEEK_END);
    int nFileLen = ftell(fp2);
    fseek(fp2,0,SEEK_SET);
    
	fread(Buffer,1,nFileLen,fp2);
	if(argv[2][0] == '1')
    printf("文件大小:%d\n",nFileLen); //获取文件大小 
    
    int j=0;
	for(uint32_t i=0;i<nFileLen;i++)
	{
		if(argv[2][1] == '2')
		{

	    if(i%16==0)
	    {
			printf("\n第[%5d]行:   ",j++);
		}
		
		printf("%02X  ",Buffer[i]);
		}
		BUF[i] = Buffer[i];
	}
	
	//校验结果低8位填充到bin末尾 
	uint32_t CrcResult = crc32(BUF,nFileLen);
	if(argv[2][0] == '1')
	printf("\nCRC校验结果:%X",CrcResult);
	fseek(fp2, 0, SEEK_END);
	ASD[1] = CrcResult >> 8;
	ASD[0] = CrcResult;
	fwrite(ASD, 2, 1, fp2);
	fclose(fp2);
	
	
	
	
	
	//接下来保存日志 
	freopen("alog.ud", "a+", stdout); 
	time_t t;
    struct tm * lt;
    time (&t);//获取Unix时间戳。
    lt = localtime (&t);//转为时间结构。
    printf ( "%d/%d/%d %d:%d:%d . %s .文件大小:%d .CRC:%08X \n",lt->tm_year+1900, lt->tm_mon+1, lt->tm_mday,\
	                                    lt->tm_hour, lt->tm_min, lt->tm_sec,argv[1],nFileLen,CrcResult);//输出结果
	fclose(stdout);
	
	return 0   ;
}














